/*
* @(#)ListDmsAuditTrailAction.java
*
* Copyright (c) 2003 DCIVision Ltd
* All rights reserved.
*
* This software is the confidential and proprietary information of DCIVision
* Ltd ("Confidential Information").  You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the license
* agreement you entered into with DCIVision Ltd.
*/
package com.dcivision.dms.web;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.audit.bean.AuditTrail;
import com.dcivision.audit.dao.AuditTrailDAObject;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsRoot;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.dms.dao.DmsRootDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.PermissionManager;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractListAction;
import com.dcivision.framework.web.AbstractSearchForm;


/**
 * <p>Class Name:       ListDmsAuditTrailAction.java    </p>
 * <p>Description:      The list action class for ListAuditTrail.jsp</p>
 *
 *    @author           Zoe Shum
 *    @company          DCIVision Limited
 *    @creation date    18/09/2003
 *    @version          $Revision: 1.18.2.4 $
 */

public class ListDmsAuditTrailAction extends AbstractListAction {

  public static final String REVISION = "$Revision: 1.18.2.4 $";


  /**
   *  Constructor - Creates a new instance of ListAuditTrailAction and define the default listName.
   */
  public ListDmsAuditTrailAction() {
    super();
    this.setListName("dmsAuditTrailList");
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.audit.dao.AuditTrailDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.DMS_AUDIT_TRAIL);
  }

  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    ListDmsAuditTrailForm actionForm = (ListDmsAuditTrailForm)form;
    
    if (!Utility.isEmpty(actionForm.getCurFunctionCode())) {
      this.setFunctionCode(actionForm.getCurFunctionCode());
    } else {
      this.setFunctionCode(null);
    }
    AbstractSearchForm searchForm = (AbstractSearchForm)form;
    if(GlobalConstant.OP_MODE_LIST_DELETE.equals(searchForm.getOpMode())){
      return super.execute(mapping, form, request, response);
    }else{
      ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
      if (forward!=null) {
         return forward;
      }
      this.getListData(mapping, searchForm, request, response);
      return mapping.findForward(GlobalConstant.NAV_MODE_LIST);
    }

  }

  public void getListData(ActionMapping mapping,AbstractSearchForm searchForm,HttpServletRequest request,HttpServletResponse response) throws ApplicationException{

    SessionContainer sessionContainer=this.getSessionContainer(request);
    Connection conn=this.getConnection(request);
    AuditTrailDAObject auditTrailDAO=new AuditTrailDAObject(sessionContainer,conn);
    DocumentRetrievalManager documentRetrievalManager = new DocumentRetrievalManager(sessionContainer,conn);
    List auditList=new ArrayList();
    
    ListDmsAuditTrailForm actionForm=(ListDmsAuditTrailForm)searchForm;
    
    if (!SystemParameterFactory.getSystemParameterBoolean(SystemParameterConstant.DMS_DISPLALY_NO_ACCESS_DOCUUMENT)){
    	auditList = this.getAccessListData(actionForm,request);
    } else {
      List childIDs = new ArrayList();
      String objectID = request.getParameter("objectID");
      if( !Utility.isEmpty(objectID)) {
        childIDs.add(Integer.valueOf(objectID));
      }
    	auditList=auditTrailDAO.getListByUserID(searchForm,childIDs);
    }
    
    if(!Utility.isEmpty(request.getParameter("userRecordID"))){
      actionForm.setUserRecordID(request.getParameter("userRecordID"));
    }
    request.setAttribute(this.getListName(),auditList);
  }
  
  public List getDocList(AbstractSearchForm form, HttpServletRequest request) throws ApplicationException {
  	List docList = new ArrayList();
  	ListDmsAuditTrailForm docForm = (ListDmsAuditTrailForm)form;
  	Connection conn = this.getConnection(request);
  	SessionContainer sessionContainer = this.getSessionContainer(request);
    DocumentRetrievalManager documentRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
  	PermissionManager pm = sessionContainer.getPermissionManager();
  	
  	DocumentRetrievalManager docRetrieval = new DocumentRetrievalManager(sessionContainer,conn);
  	DmsDocumentDAObject documentDAO = new DmsDocumentDAObject(sessionContainer,conn);
  	DmsRootDAObject dmsRootDAO = new DmsRootDAObject(sessionContainer,conn);
    
    AuditTrailDAObject auditTrailDAO=new AuditTrailDAObject(sessionContainer,conn);
    List tmpDocList = new ArrayList();
    if (!Utility.isEmpty(docForm.getParentID()) && !Utility.isEmpty(docForm.getRootID())) {
      List childIDs = new ArrayList();
      List objectIDs = new ArrayList();
      objectIDs.add(Integer.valueOf(docForm.getParentID()));
      childIDs = documentRetrievalManager.getAllsubFolderDocIDsByObjectID(objectIDs, Integer.valueOf(docForm.getRootID()));
      tmpDocList = auditTrailDAO.getList(docForm, childIDs);
    } else {
      tmpDocList = auditTrailDAO.getFullList(docForm);
    }
    
    if (tmpDocList != null){
     	for (int i=0;tmpDocList.size()>i;i++){
    		AuditTrail auditTrail = (AuditTrail)tmpDocList.get(i);
    		Integer docID = auditTrail.getObjectID();
    		DmsDocument dmsDoc = (DmsDocument)documentDAO.getObjectByID(docID);
    		
    		//when audit hard delete dmsDocument, may be the dmsDoc == null. 
    		if(dmsDoc == null) {
    		  docList.add(auditTrail);
    		  continue;
    		}
    		
    		if (DmsDocument.DOCUMENT_LINK.equals(dmsDoc.getDocumentType())){    			
    			DmsDocument tmpDoc = docRetrieval.getRelationshipTargetDocument(dmsDoc.getID(),DmsDocument.DOCUMENT_LINK);
    			if (tmpDoc == null) {
            continue;
          }
    			DmsRoot dmsRoot = (DmsRoot)dmsRootDAO.getObjectByID(tmpDoc.getRootID());  
    			
      		if (pm.hasAccessRight(conn,GlobalConstant.OBJECT_TYPE_DOCUMENT,tmpDoc.getID(),"R") || dmsRoot.getOwnerID().equals(this.getSessionContainer(request).getUserRecordID())){
      			docList.add(auditTrail);
      		} 
    		} else {
    			DmsRoot dmsRoot = (DmsRoot)dmsRootDAO.getObjectByID(dmsDoc.getRootID());
      		if (pm.hasAccessRight(conn,GlobalConstant.OBJECT_TYPE_DOCUMENT,dmsDoc.getID(),"R") || dmsRoot.getOwnerID().equals(this.getSessionContainer(request).getUserRecordID())){
      			docList.add(auditTrail);
      		}
    		} 		      
    	}
    }
    
  	return docList;
  }
  
  public List getPageList(AbstractSearchForm form, HttpServletRequest request) throws ApplicationException {

  	ListDmsAuditTrailForm docForm = (ListDmsAuditTrailForm)form;
  	List result = new ArrayList();
  	int pageSize = TextUtility.parseInteger(docForm.getPageOffset());
  	
  	while (result.size() < pageSize){
			List tmpList = this.getDocList(docForm,request);
			if (tmpList == null || tmpList.size() < 1) {
        break;
      } 
			for (int k = 0; tmpList.size() > k; k++){
				if (result.size() >= pageSize) {
          break;
        }
				result.add(tmpList.get(k));
	  }
			docForm.setCurStartRowNo(TextUtility.parseInteger(docForm.getCurStartRowNo()) + pageSize + "");
		}
  	return result;
  }
  
  public String getCurPageCursor(String cursor,int CurPageNo){
  	String curCursor = "1";
  	if (Utility.isEmpty(cursor)) {
      return curCursor;
    }
  	StringTokenizer cursorToken = new StringTokenizer(cursor,";");
  	
  	while (cursorToken.hasMoreTokens()){
  		String tmpCursor = cursorToken.nextToken();
  		if (tmpCursor.indexOf(CurPageNo + "-") != -1){
  			StringTokenizer tmpToken = new StringTokenizer(tmpCursor,"-");
  			tmpToken.nextToken();
  			curCursor  = tmpToken.nextToken();
  		}
  	}
  	return curCursor;
  }
  
  public List getAccessListData(AbstractSearchForm form, HttpServletRequest request) throws ApplicationException {
  	ListDmsAuditTrailForm docSearchForm = (ListDmsAuditTrailForm)form;
  	Integer pageAmountInc = SystemParameterFactory.getSystemParameterInteger(SystemParameterConstant.DMS_LIST_PAGEAMOUNT);
		List result = new ArrayList();
		int pageSize = TextUtility.parseInteger(docSearchForm.getPageOffset());
		int curPageNo = TextUtility.parseInteger(docSearchForm.getCurPageNO());
		int lastPageNo = TextUtility.parseInteger(docSearchForm.getLastPageNO());
		int pageAmount = TextUtility.parseInteger(docSearchForm.getPageAmount());	
		
		StringBuffer cursor = null;
		if (docSearchForm.getCursor() != null){
			cursor = new StringBuffer(docSearchForm.getCursor());
		} else {
			cursor = new StringBuffer();
		}
		
		if (curPageNo == 0 || curPageNo == 1){
			curPageNo = 0;
			cursor.delete(0,cursor.length());
		}
		
		//get list Date
		String startRowNo = this.getCurPageCursor(cursor.toString(),curPageNo);
		docSearchForm.setCurStartRowNo(startRowNo);
		result = this.getPageList(docSearchForm,request);
		
		//get cursor
		List cursorList = new ArrayList();
		AuditTrail tmpDoc = null;
		
		if (curPageNo == lastPageNo || curPageNo == 0){
			//page = 1
			if (!(result.size() < pageSize)){
				//set start page cursor
  			tmpDoc = (AuditTrail)result.get(pageSize-1);
  			if (tmpDoc != null){
  				docSearchForm.setCurStartRowNo(tmpDoc.getRowNum()+1 + "");
  			}
  			
  			int loopTimes = 0;
  			if (curPageNo == 0){
  				loopTimes = 1;
  				lastPageNo = 1;
  			}
  			
  			for (;loopTimes<pageAmountInc.intValue(); loopTimes++){
  				cursorList = this.getPageList(docSearchForm,request);
  				
  				if (!Utility.isEmpty(cursorList)){
  					tmpDoc = (AuditTrail)cursorList.get(0);
  					++lastPageNo;
  					pageAmount = lastPageNo;
  					cursor.append(lastPageNo);
  					cursor.append("-");
  					cursor.append(tmpDoc.getRowNum());
  					cursor.append(";");     				
    				
  					if (!(cursorList.size() < pageSize)){
  						tmpDoc = (AuditTrail)cursorList.get(pageSize-1);
    					if (tmpDoc == null) {
                break;
              }
    					docSearchForm.setCurStartRowNo(tmpDoc.getRowNum()+1 + "");
  					} else {
  						lastPageNo = -1;
  						break;
  					}
  					
  				} else {
  					lastPageNo = -1;
  				}    				
    		} 
  			
  			if (lastPageNo != -1 && lastPageNo == curPageNo + pageAmountInc.intValue()){
  				cursorList = this.getPageList(docSearchForm,request);
  				if (Utility.isEmpty(cursorList)) {
            lastPageNo = -1;
          }
  			}
  			
  		}       			
		}
		
		if (curPageNo == 0) {
      curPageNo = 1;
    }
		docSearchForm.setCursor(cursor.toString());
		docSearchForm.setPageAmount(pageAmount + "");
		docSearchForm.setCurPageNO(curPageNo + "");
		docSearchForm.setLastPageNO(lastPageNo + "");
		docSearchForm.setPageAmount(pageAmount + "");
		return result;
  }
}

